/*
 *  Copyright 2007 Blandware (http://www.blandware.com)
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.blandware.atleap.webapp.action.core.sequenceItem;

import com.blandware.atleap.common.Constants;
import com.blandware.atleap.model.core.ActionPage;
import com.blandware.atleap.model.core.ContentDocument;
import com.blandware.atleap.model.core.ContentImage;
import com.blandware.atleap.model.core.ContentPage;
import com.blandware.atleap.model.core.ContentResource;
import com.blandware.atleap.model.core.Localizable;
import com.blandware.atleap.model.core.Sequence;
import com.blandware.atleap.model.core.SequenceItem;
import com.blandware.atleap.model.forum.Forum;
import com.blandware.atleap.model.forum.Post;
import com.blandware.atleap.model.news.NewsItem;
import com.blandware.atleap.model.questionnaire.Questionnaire;
import com.blandware.atleap.model.testimonials.Testimonial;
import com.blandware.atleap.service.core.SequenceManager;
import com.blandware.atleap.webapp.action.core.BaseAction;
import com.blandware.atleap.webapp.form.core.SequenceItemForm;
import com.blandware.atleap.webapp.util.core.WebappConstants;
import com.blandware.atleap.webapp.util.core.WebappUtil;
import org.apache.commons.validator.GenericValidator;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * <p>Exposes bean to request to view its properties on JSP page (sequence item
 * is to be viewed)
 * </p>
 * <p><a href="ViewSequenceItemAction.java.html"><i>View Source</i></a></p>
 * <p/>
 *
 * @author Roman Puchkovskiy <a href="mailto:roman.puchkovskiy@blandware.com">
 *         &lt;roman.puchkovskiy@blandware.com&gt;</a>
 * @version : $Revision: 1.5 $ : 2007/12/17 13:38:25 $
 * @struts.action path="/core/sequenceItem/view"
 * name="sequenceItemForm"
 * scope="request"
 * validate="false"
 * roles="core-sequenceItem-view"
 * @struts.action-forward name="viewSequenceItem"
 * path=".core.sequenceItem.view"
 * @struts.action-forward name="listSequenceItems"
 * path="/core/sequenceItem/list.do"
 * redirect="false"
 * @struts.action-forward name="viewContentPage"
 * path="/core/contentPage/view.do"
 * @struts.action-forward name="viewActionPage"
 * path="/core/actionPage/view.do"
 * @struts.action-forward name="viewNewsItem"
 * path="/news/viewItem.do"
 * @struts.action-forward name="viewTestimonial"
 * path="/testimonials/viewTestimonial.do"
 * @struts.action-forward name="viewForum"
 * path="/forum/forum/view.do"
 * @struts.action-forward name="showPost"
 * path="/forum/post/show.do"
 * @struts.action-forward name="viewQuestionnaire"
 * path="/questionnaire/questionnaire/view.do"
 * @struts.action-forward name="viewDocument"
 * path="/core/contentResource/document/view.do"
 * @struts.action-forward name="viewImage"
 * path="/core/contentResource/image/view.do"
 * @struts.action-forward name="viewFile"
 * path="/core/contentResource/file/view.do"
 */
public final class ViewSequenceItemAction extends BaseAction {
	/**
	 * @param mapping  The ActionMapping used to select this instance
	 * @param form     The optional ActionForm bean for this request (if any)
	 * @param request  The HTTP request we are proceeding
	 * @param response The HTTP response we are creating
	 * @return an ActionForward instance describing where and how
	 *         control should be forwarded, or null if response
	 *         has already been completed
	 */
	public ActionForward execute(ActionMapping mapping, ActionForm form,
	                             HttpServletRequest request, HttpServletResponse response) throws Exception {

		SequenceItemForm sequenceItemForm = (SequenceItemForm) form;

		Long sequenceItemId;
		if ( !GenericValidator.isBlankOrNull(sequenceItemForm.getId()) ) {
			sequenceItemId = Long.valueOf(sequenceItemForm.getId());
		} else {
			Long sequenceId;
			if ( sequenceItemForm.getSequenceId() != null && sequenceItemForm.getSequenceId().length() > 0 ) {
				sequenceId = Long.valueOf(sequenceItemForm.getSequenceId());
			} else {
				if ( log.isWarnEnabled() ) {
					log.warn("Missing sequence ID. Returning to index...");
				}
				return mapping.findForward("admin");
			}

			request.getSession().setAttribute(WebappConstants.SEQUENCE_ID_KEY, sequenceId);

			if ( log.isWarnEnabled() ) {
				log.warn("Missing sequence item ID. Returning to list...");
			}

			return mapping.findForward("listSequenceItems");
		}

		SequenceManager sequenceManager = (SequenceManager) getBean(Constants.SEQUENCE_MANAGER_BEAN);
		SequenceItem sequenceItem = sequenceManager.retrieveSequenceItem(sequenceItemId);
		if ( sequenceItem == null ) {
			// sequence item not found. it might be deleted by someone else
			ActionMessages errors = new ActionMessages();
			errors.add("sequenceItemNotFound", new ActionMessage("core.sequenceItem.errors.notFound"));
			saveErrors(request, errors);
			return mapping.findForward("listSequenceItems");
		}

		request.setAttribute("sequenceItem", sequenceItem);

		// get information about owner
        Sequence sequence = sequenceItem.getSequence();
        Localizable owner = sequence.getOwner();
		String ownerInfo = WebappUtil.getLocalizableInfo(owner, request);
		request.getSession().setAttribute(WebappConstants.OWNER_INFO_KEY, ownerInfo);

        // calculate action to use for viewing object
        // TODO: need a way to avoid explicit enumerating of classes which are not in core module
        String objectViewAction = null;
        if (sequenceItem.getPage() != null) {
            if (sequenceItem.getPage() instanceof ContentPage) {
                objectViewAction = mapping.findForward("viewContentPage").getPath();
            } else if (sequenceItem.getPage() instanceof ActionPage) {
                objectViewAction = mapping.findForward("viewActionPage").getPath();
            } else if (sequenceItem.getPage() instanceof NewsItem) {
                objectViewAction = mapping.findForward("viewNewsItem").getPath();
            } else if (sequenceItem.getPage() instanceof Testimonial) {
                objectViewAction = mapping.findForward("viewTestimonial").getPath();
            } else if (sequenceItem.getPage() instanceof Forum) {
                objectViewAction = mapping.findForward("viewForum").getPath();
            } else if (sequenceItem.getPage() instanceof Post) {
                objectViewAction = mapping.findForward("showPost").getPath();
            } else if (sequenceItem.getPage() instanceof Questionnaire) {
                objectViewAction = mapping.findForward("viewQuestionnaire").getPath();
            }
        } else {
            if (sequenceItem.getContentResource() instanceof ContentDocument) {
                objectViewAction = mapping.findForward("viewDocument").getPath();
            } else if (sequenceItem.getContentResource() instanceof ContentImage) {
                objectViewAction = mapping.findForward("viewImage").getPath();
            } else if (sequenceItem.getContentResource() instanceof ContentResource) {
                objectViewAction = mapping.findForward("viewFile").getPath();
            }
        }
        request.setAttribute("objectViewAction", objectViewAction);

        saveToken(request);
		return mapping.findForward("viewSequenceItem");
	}
}